package com.kara.woodAgent.agent.wood.node;

import com.alibaba.fastjson2.JSON;
import com.kara.woodAgent.agent.graph.Next;
import com.kara.woodAgent.agent.graph.Node;
import com.kara.woodAgent.agent.wood.context.WoodContext;
import com.kara.woodAgent.agent.wood.model.Plan;
import com.kara.woodAgent.common.exception.BizException;


/**
 * @author tzy
 * @version 1.0
 * @project wood_agent
 * @description
 * @date 2025/6/10 10:43:22
 */

public class DispatchNode implements Node<WoodContext> {


	@Override
	public Next execute(WoodContext context) {


		if (context.getCurrentPlan() == null && context.getCurrentPlanId() == null) {
			//初始化
			context.setCurrentPlanId(-1);
			return toNext(context);
		} else {
			Plan currentPlan = context.getCurrentPlan();
			if (Plan.SUCCESS.equals(currentPlan.getStatus())) {
				return toNext(context);
			} else if (Plan.FAIL.equals(currentPlan.getStatus())) {
				//todo 返回给重归化节点
				return toRePlan(currentPlan,context);
			} else {
				throw new BizException("计划状态异常：" + JSON.toJSONString(currentPlan));
			}

		}

	}

	private Next toRePlan(Plan currentPlan, WoodContext context) {

		return Next.NextNode("rePlan").step(JSON.toJSONString(currentPlan));
	}

	private Next toNext(WoodContext context) {

		Plan nextPlan = context.getNextPlan();
		if (nextPlan != null) {
			// 调用模型
			nextPlan.running();
			context.setCurrentPlan(nextPlan);
			return Next.NextNode("executor").step(JSON.toJSONString(nextPlan));
		}
		return Next.End().step("over");
	}
}
